from pylab import *
import numpy as np
import matplotlib.pyplot as plt
import os
class flight:
    def __init__(self,_id,origin_name,origin_iata,origin_code,destination_name,destination_iata,destination_code,airline_code,airline_name,airline_iata,flight_number,departure_time,departure_time_actual,arrival_time,arrival_time_actual,aircraft_type,a_arrival_time_gate,s_arrival_time_gate,a_departure_time_gate,s_departure_time_gate,a_runway_arrival,a_runway_departure,missing_info):
        self.id = _id
        self.origin_name = origin_name
        self.origin_iata = origin_iata
        self.origin_icao = origin_code

        self.destination_name = destination_name
        self.destination_iata = destination_iata
        self.destination_icao = destination_code

        self.airline_code = airline_code
        self.airline_name = airline_name
        self.airline_iata = airline_iata
        self.flight_number = flight_number

        self.departure_time = departure_time
        self.arrival_time = arrival_time
        self.departure_time_actual = departure_time_actual
        self.arrival_time_actual = arrival_time_actual
        self.a_departure_time_gate = int(a_departure_time_gate)
        self.a_arrival_time_gate = int(a_arrival_time_gate)
        self.s_departure_time_gate = int(s_departure_time_gate)
        self.s_arrival_time_gate = int(s_arrival_time_gate)
        self.a_runway_arrival = int(a_runway_arrival)
        self.a_runway_departure = int(a_runway_departure)
        self.aircraft_type = aircraft_type
        self.missing_info = missing_info

class simpleflight:
    def __init__(self,_id,a_runway_departure,a_departure_time_gate,missing_info):
        self._id = _id
        self.a_runway_departure = int(a_runway_departure)
        self.a_departure_time_gate = int(a_departure_time_gate)
        self.missing_info = missing_info

class analyse:       
    def __init__(self,filename='mumbai.npz'):
        self.filename = filename.replace('.npz','')
        file_ = np.load(filename)
        os.chdir('/home/anand/Dropbox/flightdata')
        file_a = np.load('airport.npz')
        self.flights = file_['flights']
        self.i = file_a['i']
        self.d = file_a['d']
        self.orig = file_['orig']
        self.des = file_['des']
        print len(self.orig),len(self.des)
    def _print_flight_details(self,flight):
        f = flight
        print f.id,f.origin_name,f.destination_name,f.arrival_time,f.departure_time,f.airline_name

    def _test(self):
        for i in self.flights:
            self._print_flight_details(i)
    def _get_airports_code_list(self):
        alist = []
        for i in self.flights:
            if i.origin_iata not in alist:
                alist.append(i.origin_iata)
            if i.destination_iata not in alist:
                alist.append(i.destination_iata)
        return alist

    def _sep_airports_(self):
        tmp = self._get_airports_code_list()
        international = []
        domestic = []
        for i in tmp:
            print i
            var = raw_input('i/d?')
            if var == 'i':
                international.append(i)
            elif var == 'd':
                domestic.append(i)
        print international,domestic
        print len(international),len(domestic)
        savez('airport.npz',d=domestic,i=international)
    def _divide_in_time(self,n=24):
        d_landings = []
        d_takeoffs = []
        i_landings = []
        i_takeoffs = []

        dt = 15
        tim = range((n)*4)
        
        ttime = []
        for i in range(n):
            for kk in range(1,5):
                d_landing_count = 0
                d_takeoff_count = 0
                i_landing_count = 0
                i_takeoff_count = 0
               
                for j in self.orig:
                    departure_time = j.departure_time
                    if departure_time >= i*100+(kk-1)*dt:
                        if departure_time < i*100 + kk*dt:
                            if j.destination_iata in self.d:
                                d_takeoff_count += 1
                            else:
                                i_takeoff_count += 1
                                
                                
                            
                for j in self.des:
                    arrival_time = j.arrival_time
                        
                    if arrival_time >= i*100+(kk-1)*dt:
                        if arrival_time < i*100 + kk*dt:
                            if j.origin_iata in self.d:
                                d_landing_count += 1
                            else:
                                i_landing_count += 1
                                
                                
                                
                d_landings.append(d_landing_count)
                d_takeoffs.append(d_takeoff_count)
                i_landings.append(i_landing_count)
                i_takeoffs.append(i_takeoff_count)
                ttime.append(i*100+kk*dt)
        print sum(d_landings),sum(d_takeoffs),sum(i_landings),sum(i_takeoffs)
        print len(d_landings),len(d_takeoffs),len(i_landings),len(i_takeoffs)
        

        figure(figsize=(11, 8.5))
        d_landings = array(d_landings)
        d_takeoffs = array(d_takeoffs)
        i_landings = array(i_landings)
        i_takeoffs = array(i_takeoffs)
        width = 15
        tim = array(tim)
        tmp = []
        tmptmp = []
        count = 0
        for i in range(96):
            if i%4 == 0:
                tmp.append(i*25+45)
                tmptmp.append(count)
                count += 1
                
        tmp = array(tmp)
        tmptmp = array(tmptmp)
        f = gca()
        grid(color='k', linestyle='-.', linewidth=.5)
        f.xaxis.grid(False)
        p1 = plt.bar(ttime,d_landings, width, color='r')
        p2 = plt.bar(ttime,d_takeoffs, width, color='y',bottom=d_landings)
        p3 = plt.bar(ttime,i_landings, width, color='b',bottom=(d_landings + d_takeoffs))
        p4 = plt.bar(ttime,i_takeoffs, width, color='g',bottom=(i_landings +d_takeoffs+d_landings))
        axhline(y=8,color='k')
        
        plt.ylabel('No. of Operations')
        plt.title('Airport: Mumbai')
        plt.xticks( tmp, tmptmp )
        plt.xlabel('Time in Hours')
        plt.yticks(np.arange(0,15,1))
        plt.legend( (p1[0], p2[0],p3[0],p4[0]), ('Domestic Landings','Domestic Takeoffs','International Landings','International Takeoffs') )
        #plt.show()
        os.chdir('/home/anand/Dropbox/flightdata/')
        savefig(self.filename + '.png')
    def _simple_divide_in_time(self):
        landings = []
        takeoffs = []
        n=24
        dt = 15
        tim = range((n)*4)
       
        ttime = []
        for i in range(n):
            for kk in range(1,5):
                landing_count = 0
                takeoff_count = 0
                
               
                for j in self.orig:
                    departure_time = j.departure_time
                    if departure_time >= i*100+(kk-1)*dt:
                        if departure_time < i*100 + kk*dt:
                            takeoff_count += 1
                                
                            
                for j in self.des:
                    arrival_time = j.arrival_time
                        
                    if arrival_time >= i*100+(kk-1)*dt:
                        if arrival_time < i*100 + kk*dt:
                            landing_count += 1
                
               

                landings.append(landing_count)
                takeoffs.append(takeoff_count)
                ttime.append(i*100+kk*dt)
                
        figure(figsize=(11, 8.5))
        landings = array(landings)
        takeoffs = array(takeoffs)
        width = 15
        tim = array(tim)
        tmp = []
        tmptmp = []
        count = 0
        for i in range(96):
            if i%4 == 0:
                tmp.append(i*25+45)
                tmptmp.append(count)
                count += 1
                
        tmp = array(tmp)
        tmptmp = array(tmptmp)
        f = gca()
        grid(color='k', linestyle='-.', linewidth=.5)
        f.xaxis.grid(False)
        p1 = plt.bar(ttime,landings, width, color='r')
        p2 = plt.bar(ttime,takeoffs, width, color='y',bottom=landings)
        
        axhline(y=8,color='k')
        
        plt.ylabel('No. of Operations')
        plt.title('Airport: '+ self.filename)
        plt.xticks( tmp, tmptmp )
        plt.xlabel('Time in Hours')
        #plt.yticks(np.arange(0,15,1))
        plt.legend( (p1[0], p2[0]), ('Landings','Takeoffs') )
        #plt.show()
        os.chdir('/home/anand/Dropbox/flightdata/png/')
        savefig(self.filename+'.png')

    def _study_delay(self):
        landings = []
        takeoffs = []
        n=24
        dt = 15
        tim = range((n)*4)
        arrival_avg_delay = []
        departure_avg_delay = []
        ttime = []
        for i in range(n):
            for kk in range(1,5):
                landing_count = 0
                takeoff_count = 0
                arrival_delay_count = 0
                departure_delay_count = 0
                tmp_l_count = 0
                tmp_t_count = 0
                for j in self.orig:
                    departure_time = j.a_departure_time_gate
                    if departure_time >= i*100+(kk-1)*dt:
                        if departure_time < i*100 + kk*dt:
                            takeoff_count += 1.
                            tmp_delay = j.a_departure_time_gate - j.s_departure_time_gate 
                           
                            if tmp_delay > 15 and tmp_delay < 120:
                                departure_delay_count += tmp_delay
                                tmp_t_count += 1    
                            
                for j in self.des:
                    arrival_time = j.a_arrival_time_gate
                    if arrival_time >= i*100+(kk-1)*dt:
                        if arrival_time < i*100 + kk*dt:
                            landing_count += 1.
                            tmp_delay = j.a_arrival_time_gate - j.s_arrival_time_gate
                            if tmp_delay > 15 and tmp_delay < 120:
                                arrival_delay_count += tmp_delay
                                tmp_l_count += 1
                if tmp_l_count != 0:
                    arrival_avg_delay.append(arrival_delay_count/float(landing_count+takeoff_count))
                    
                else:
                    arrival_avg_delay.append(0)
                if tmp_t_count != 0:
                    departure_avg_delay.append(departure_delay_count/float(tmp_t_count))
                    print tmp_t_count/float(takeoff_count)*100
                else:
                    departure_avg_delay.append(0)
                
                landings.append(landing_count)
                takeoffs.append(takeoff_count)
                ttime.append(i*100+kk*dt)
        landings = array(landings)
        takeoffs = array(takeoffs)
        arrival_avg_delay = array(arrival_avg_delay)
        departure_avg_delay = array(departure_avg_delay)
        #figure()
        #title('Landings')
        #bar(landings+takeoffs,arrival_avg_delay+departure_avg_delay)
        figure()
        title('Takeoffs')
        bar(takeoffs+landings,departure_avg_delay)
        show()

    def _mit_study_delay(self):
        landings = []
        takeoffs = []
        n=24
        dt = 15
        tim = range((n)*4)
        arrival_avg_delay = []
        departure_avg_delay = []
        ttime = []
        queue = []
        for i in range(n):
            for kk in range(1,5):
                landing_count = 0
                takeoff_count = 0
                arrival_delay_count = 0
                departure_delay_count = 0
                tmp_l_count = 0
                tmp_t_count = 0
                departure_queue = 0
                for j in self.orig:
                    departure_time = j.a_departure_time_gate
                    if departure_time >= i*100+(kk-1)*dt:
                        if departure_time < i*100 + kk*dt:
                            takeoff_count += 1.
                            tmp_delay = j.a_departure_time_gate - j.s_departure_time_gate 
                           
                            if tmp_delay > 15 and tmp_delay < 120:
                                departure_delay_count += tmp_delay
                                tmp_t_count += 1    
                    if j.a_departure_time_gate <= i*100+(kk-1)*dt:
                        if j.a_runway_departure >= i*100+(kk)*dt:
                            departure_queue += 1
                for j in self.des:
                    arrival_time = j.a_arrival_time_gate
                    if arrival_time >= i*100+(kk-1)*dt:
                        if arrival_time < i*100 + kk*dt:
                            landing_count += 1.
                            tmp_delay = j.a_arrival_time_gate - j.s_arrival_time_gate
                            if tmp_delay > 15 and tmp_delay < 120:
                                arrival_delay_count += tmp_delay
                                tmp_l_count += 1
                if tmp_l_count != 0:
                    arrival_avg_delay.append(arrival_delay_count/float(landing_count+takeoff_count))
                    
                else:
                    arrival_avg_delay.append(0)
                if tmp_t_count != 0:
                    departure_avg_delay.append(departure_delay_count/float(tmp_t_count))
                else:
                    departure_avg_delay.append(0)
                print departure_queue
                queue.append(departure_queue)
                landings.append(landing_count)
                takeoffs.append(takeoff_count)
                ttime.append(i*100+kk*dt)
        landings = array(landings)
        takeoffs = array(takeoffs)
        arrival_avg_delay = array(arrival_avg_delay)
        departure_avg_delay = array(departure_avg_delay)
        #figure()
        #title('Landings')
        #bar(landings+takeoffs,arrival_avg_delay+departure_avg_delay)
        figure()
        title('Takeoffs')
        queue_unique = []
        takeoff_unique = []
        for i in range(len(takeoffs)):
            takeoffs.pop(takeoffs.index(i))
            avg = i
            count = 1
            for j in range(len(takeoffs)):
                if i==j:
                    avg +=j
                    takeoffs.pop(takeoffs.index(j))
                    count += 1
            
        plot(queue,takeoffs,'o')
        #bar(takeoffs+landings,departure_avg_delay)
        show()

airport =[u'DEL',
 u'BOM',
 u'LKO',
 u'HYD',
 u'BLR',
 u'RAJ',
 u'JNB',
 u'HKG',
 u'BDQ',
 u'BKK',
 u'IXU',
 u'IXB',
 u'CDG',
 u'PVG',
 u'TRV',
 u'GOI',
 u'UDR',
 u'DMM',
 u'SIN',
 u'BBI',
 u'MCT',
 u'JDH',
 u'PAT',
 u'CCU',
 u'CJB',
 u'KUL',
 u'BAH',
 u'BHJ',
 u'PBD',
 u'HHN',
 u'MAA',
 u'JAI',
 u'DOH',
 u'NAG',
 u'AMD',
 u'CMB',
 u'COK',
 u'ZRH',
 u'RUH',
 u'IXE',
 u'IXR',
 u'IST',
 u'BRU',
 u'JED',
 u'BHU',
 u'VNS',
 u'MUC',
 u'IXC',
 u'AUH',
 u'AMS',
 u'IDR',
 u'DXB',
 u'IXY',
 u'LHR',
 u'KWI',
 u'NDC',
 u'SHJ',
 u'CCJ',
 u'NBO',
 u'PNQ',
 u'ADD',
 u'GWL',
 u'NRT',
 u'JGA',
 u'RPR',
 u'HBX',
 u'FRA',
 u'IXG',
 u'BHO',
 u'IXL',
 u'KTM',
 u'ISK',
 u'CAI',
 u'DAC',
 u'EWR',
 u'VIE',
 u'DIU']

# for i in airport:
#     os.chdir('/home/anand/Dropbox/flightdata/npz')
#     a = analyse(filename=i+'.npz')
#     a._simple_divide_in_time()
